package com.xiantm.study.thread.readwritelock;


import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.Lock;

public class Data{
    private final char[] buffer;
    //    private final ReadWriteLock lock = new ReadWriteLock();
//    private final char[] buffer;
    private final java.util.concurrent.locks.ReadWriteLock lock = new ReentrantReadWriteLock(true);
    private final Lock readLock = lock.readLock();
    private final Lock writeLock = lock.writeLock();
    public Data(int size) {
        this.buffer = new char[size];
        for (int i = 0; i < size; i++) {
            buffer[i] = '*';
        }
    }

    public char[] read() throws InterruptedException{
//        lock.readLock();
        readLock.lock();
        try {
            return doRead();
        }finally {
//            lock.readUnlock();
            readLock.unlock();
        }
    }

    public void write(char c) throws InterruptedException{
//        lock.writeLock();
        writeLock.lock();
        try {
            doWrite(c);
        } finally {
//           lock.writeUnlock();
            writeLock.unlock();
        }
    }



    private char[] doRead(){
        char[] newBuf = new char[buffer.length];
        for (int i = 0; i < buffer.length; i++) {
            newBuf[i] = buffer[i];
        }
        slowly();
        return newBuf;
    }

    private void doWrite(char c){
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = c;
            slowly();
        }
    }



    private void slowly(){
        try {
            Thread.sleep(50);
        }catch (InterruptedException e){

        }
    }
}

